package com.unswift.cloud.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiField;
import com.unswift.annotation.api.ApiMethod;
import com.unswift.utils.ObjectUtils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@Api(value="获取Servlet各对象", author="unswift", date="2023-06-01", version="1.0.0")
public final class ServletUtils {
	
	@ApiMethod(value="获取Servlet的request对象", returns=@ApiField("HttpServletRequest对象"))
	public static HttpServletRequest getRequest(){
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		if(ObjectUtils.isNotEmpty(requestAttributes)){
			return requestAttributes.getRequest();
		}
		return null;
	}
	
	@ApiMethod(value="获取Servlet的response对象", returns=@ApiField("HttpServletResponse对象"))
	public static HttpServletResponse getResponse(){
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		if(ObjectUtils.isNotEmpty(requestAttributes)){
			return requestAttributes.getResponse();
		}
		return null;
	}
	
	@ApiMethod(value="获取Servlet的session对象", returns=@ApiField("HttpSession对象"))
	public static HttpSession getSession(){
		HttpServletRequest request=getRequest();
		if(ObjectUtils.isNotEmpty(request)){
			return getRequest().getSession();
		}
		return null;
	}
	
	public static String getHeader(String key){
		HttpServletRequest request=getRequest();
		if(ObjectUtils.isNotEmpty(request)){
			return getRequest().getHeader(key);
		}
		return null;
	}
}
